
package visualisation;

import primitives.graph.*;
import primitives.cluster.*;
import translator.DOTWriter;
import search.util.*;

class ClusterDump{
	
	
	def subsume = [:]
	int n = 0;
	ClusterLeaf c;
	
	def static outEdges(IClusterLevel c){
        return edgesFilteredBy(c,{
                trans -> 
                !c.nodes.contains(trans.destinationNode)

        });
    }

	def static intraEdges(IClusterLevel c){
		return edgesFilteredBy(c,{
                trans -> 
                c.nodes.contains(trans.destinationNode)

        });
	}

	def static edgesFilteredBy(IClusterLevel c, clj){
		Collection<Transition> nodes = []
        c.nodes.each{
            node ->
            nodes.addAll(node.getTransitionsAsT().findAll(clj))
        }
        return nodes
	}

	 void printCluster(IClusterLevel tree,int d){
		int t = 0;

		if(d == 0){
			def c = new Node("_"+n);
			tree.nodes.each{
				it.transitionsAsT.each{ tx->
					c.connect(tx.getDestinationNode(), tx.getLabel());
				
				}
				subsume[it] = c
				tree.removeNode(it)
			}
			tree.addNode(c)
			n++;
		}else if(tree.encapsulates()){
			ClusterNode c = (ClusterNode) tree;
			def cd = c.children;
			cd.each{

				    	printCluster(it, d-1)
		       		}
			
		}

	}
	
	public static void main(String[] args){
		def filename = args[0]
		def count = args[1].toInteger()
		
		ClusterHead tree = TreeLoader2.loadTreeFromSerial(new File(filename))

		ClusterDump d = new ClusterDump();
		d.printCluster(tree, count)
		Graph g = new Graph();
		d.subsume.each{
			k,v ->
			v.transitionsAsT.each{
				tx ->
				if(d.subsume[tx.destinationNode] != null){
					v.connect(d.subsume[tx.destinationNode],tx.label);
					v.deleteTransition(tx);
					
				}
				
			}

		}

            FileWriter fstream = new FileWriter(filename + "_.dot");
		BufferedWriter out = new BufferedWriter(fstream);
		
		
		    out.write(new DOTWriter().getDOT(tree));
		    out.close();
		
		
	}
	

	
}